package cn.pet_know.common.aop;

import cn.pet_know.common.enums.RedisPrefix;
import cn.pet_know.common.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

@Aspect
@Component
@Slf4j
public class TimerCount {

    @Resource
    private RedisUtil redisUtil;

    @Before("execution(* cn.pet_know.controller.*.*(..))")
    public void controllerStartTimerCount(JoinPoint joinPoint) {
        // 接口启动时间
        // 获取目标类
        Class<?> clazz = joinPoint.getTarget().getClass();

        // 类名
        String className = clazz.getName();

        // redisKey
        String redisKey = RedisPrefix.CONTROLLER_TIMER_PREFIX + className + Thread.currentThread().getName();

        // 存启动时间
        redisUtil.setForValue(redisKey, System.currentTimeMillis());
    }

    @After("execution(* cn.pet_know.controller.*.*(..))")
    public void controllerEndTimerCount(JoinPoint joinPoint) {
        long nowTime = System.currentTimeMillis();
        // 获取目标类
        Class<?> clazz = joinPoint.getTarget().getClass();

        // 类名
        String className = clazz.getName();

        // redisKey
        String redisKey = RedisPrefix.CONTROLLER_TIMER_PREFIX + className + Thread.currentThread().getName();

        // 存启动时间
        Long startTime = (Long) redisUtil.getForValue(redisKey);
        if (Objects.isNull(startTime)) {
            log.error("!!! TimerCount error");
        }

        long diff = nowTime - startTime;
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String methodName = methodSignature.getName();
        log.info("方法执行 {}.{} 总耗时: {} 毫秒.", className, methodName, diff);
    }

}
